#!/bin/python3
# -*- coding:utf-8 -*-
"""
    [模块名]
    By :陈狍子 e4ting@qq.com 2025-01-01 22:09:52
"""
import sys,os
from pdb import set_trace as strace
from traceback  import format_exc as dumpstack
from e4ting import util,log

from flask_restful import Resource
from flask         import redirect,request,make_response

from app.flaskapp import webapp

import json
from e4ting.cache import TokenCache

@webapp.before_request
def _check_and_parse_token():
    request.user = {}
    token = request.headers.get("token", "")
    if not token:
        # 没登录
        request.user = {
            "username": '未登录',
        }
        return None
    cache = TokenCache(token)
    if not cache.exists():
        # 没登录
        return None

    data  = json.loads(cache.data  or "{}")
    data2 = json.loads(cache.data2 or "{}")
    request.user = {
        "phone" : cache.name,
        "name"  : data.get("displayName", ""),
        "uid"   : cache.uid,
        "type"  : data.get("type", ""),
        "avatar": data.get("avatar", ""),
        "roles" : data.get("roles", ""),
        # "" : ,
    }
    log.debug(request.user)
    return None

class WebToken(Resource):
    ''' 用来检查token '''

    # ----------------------------------------------------------------------
    def __init__(self):
        super(WebToken, self).__init__()

    def get(self, **kwargs):
        return dict(code=200, data=request.user)